import 'dart:async';

import 'package:kmxy_base/base/base_package.dart';
import 'package:kmxy_base/kmxy_base.dart';

class PatrolPermissionDialog extends StatefulWidget {
  PatrolPermissionDialog({Key? key}) : super(key: key);

  @override
  _PatrolPermissionDialogState createState() => _PatrolPermissionDialogState();
}

class _PatrolPermissionDialogState extends State<PatrolPermissionDialog> {
  StreamSubscription? _subscription;

  ///  0-未申请授权，1-同意授权，2-拒绝授权
  int locationAlwaysState = 0;
  bool ignoringBatteryOptimizations = false;
  bool systemAlertWindow = false;

  @override
  void initState() {
    initData();
    super.initState();
  }

  initData() async {
    locationAlwaysState = await PermissionUtil.getInstance
        .isRequest(context, Permission.locationAlways);

    ignoringBatteryOptimizations =
        await KmxyBase.isIgnoringBatteryOptimizations();

    systemAlertWindow = await KmxyBase.isSystemAlertWindow();
    setState(() {});
    _subscription = Event.eventBus.on<Event>().listen((event) async {
      if (PermissionUtil.getInstance.EVENT_PATROL_PERMISSION == event.type) {
        //延时执行
        Future.delayed(const Duration(milliseconds: 1000), () async {
          ignoringBatteryOptimizations =
              await KmxyBase.isIgnoringBatteryOptimizations();
          setState(() {});
        });
        locationAlwaysState = await PermissionUtil.getInstance
            .isRequest(context, Permission.locationAlways);

        systemAlertWindow = await KmxyBase.isSystemAlertWindow();
        setState(() {});
        if (locationAlwaysState == 1 &&
            ignoringBatteryOptimizations &&
            systemAlertWindow) {
          Navigator.pop(context);
        }
      }
    });
  }

  @override
  void dispose() {
    _subscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () => Future.value(true),
      child: Material(
        //创建透明层
        type: MaterialType.transparency, //透明类型
        child: Center(
          //保证控件居中效果
          child: SizedBox(
            width: MediaQuery.of(context).size.width - 30.w,
            child: Container(
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                color: Colors.white,
                // 圆角设置
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    '为了保证定位功能的准确性\n请允许以下权限”',
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 18.w),
                  ),
                  SizedBox(height: 20.w),
                  InkWell(
                    onTap: () async {
                      await PermissionUtil.getInstance.request(
                          context, Permission.locationAlways, '后台定位权限');
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 10.w),
                      child: Row(
                        children: [
                          Icon(Icons.storage, size: 26.w),
                          SizedBox(width: 10.w),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '后台定位权限',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 16.w),
                              ),
                              Text(
                                '请在定位权限设置中勾选“始终允许”',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 12.w),
                              ),
                            ],
                          ),
                          Expanded(child: Container()),
                          locationAlwaysState == 1
                              ? Icon(Icons.check_circle, size: 26.w)
                              : Text(
                                  '设置',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(fontSize: 16.w),
                                ),
                        ],
                      ),
                    ),
                  ),
                  InkWell(
                    onTap: () async {
                      KmxyBase.requestIgnoreBatteryOptimizations();
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 10.w),
                      child: Row(
                        children: [
                          Icon(Icons.storage, size: 26.w),
                          SizedBox(width: 10.w),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '忽略电池优化',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 16.w),
                              ),
                              Text(
                                '在电池策略中请允许应用在后台运行',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 12.w),
                              ),
                            ],
                          ),
                          Expanded(child: Container()),
                          ignoringBatteryOptimizations
                              ? Icon(Icons.check_circle, size: 26.w)
                              : Text(
                                  '设置',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(fontSize: 16.w),
                                ),
                        ],
                      ),
                    ),
                  ),
                  InkWell(
                    onTap: () async {
                      KmxyBase.setSystemAlertWindow();
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 10.w),
                      child: Row(
                        children: [
                          Icon(Icons.storage, size: 26.w),
                          SizedBox(width: 10.w),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '悬浮窗权限',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 16.w),
                              ),
                              Text(
                                '请选择应用并运行应用显示悬浮窗',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 12.w),
                              ),
                            ],
                          ),
                          Expanded(child: Container()),
                          systemAlertWindow
                              ? Icon(Icons.check_circle, size: 26.w)
                              : Text(
                                  '设置',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(fontSize: 16.w),
                                ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
